package com.example.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.StandardCharsets;

public class FastJson2RedisSerializer<T> implements RedisSerializer<T> {
    private static final byte[] EMPTY = new byte[0];
    private final Class<T> type;

    public FastJson2RedisSerializer(Class<T> type) { this.type = type; }

    @Override public byte[] serialize(T t) throws SerializationException {
        if (t == null) return EMPTY;
        // 只写入类名标记，不启用 AutoType 解析
        return JSON.toJSONBytes(t, JSONWriter.Feature.WriteClassName);
    }

    @Override public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) return null;
        String str = new String(bytes, StandardCharsets.UTF_8);
        // 不启用 SupportAutoType，仅按目标类型解析（安全）
        return JSON.parseObject(str, type);
    }
}
